package com.example.daxiguaforharmony.utils;

import com.example.daxiguaforharmony.slice.LoadingAbilitySlice;
import com.example.daxiguaforharmony.ui.DeviceSelectDialog;
import com.example.daxiguaforharmony.manager.CrossDevicePlayerInterfaceProxy;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.bundle.AbilityInfo;
import ohos.bundle.ElementName;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConnDevice extends AbilitySlice implements IAbilityContinuation {
    //private LoadingAbilitySlice.MyEvenHandler mHandler;

    static final HiLogLabel label=new HiLogLabel(HiLog.LOG_APP,0x0001,"获取跳转结果测试");
    private static final String TAG = LoadingAbilitySlice.class.getSimpleName();
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "LoadingAbilitySlice");

    private String data = null;

    private Operation localOperation;
    private Operation remoteOperation;
    private Operation remoteMainOperation;

    private Intent localIntent;
    private Intent remoteIntent;
    private Intent remoteMainIntent;

    public static final int CHANGE_PROGRESS=201;
    public static final int TOTAL_PROGRESS=202;
    public static final int UPDATE_PROGRESS=203;
    public static final int CURRENT_PLAY_TIME=301;
    public static final int CURRENT_SCORE=401;

    public static boolean isPlay=false;
    public static boolean isConnect=false; //是否远程
    private boolean emptyDevice;
    private Image selectDeviceButton;
    private DependentLayout cameraButtonLayout;

    private int screenWidth;
    private int screenHeight;


    private static int score=121; //分数

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    //连接本地服务
    CrossDevicePlayerInterfaceProxy localPlayerInterfaceProxy = null;
    private IAbilityConnection localAbilityConnection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            localPlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            localPlayerInterfaceProxy = null;
        }
    };

    //连接远程服务
    CrossDevicePlayerInterfaceProxy remotePlayerInterfaceProxy = null;
    private IAbilityConnection remoteAbilityConnection = new IAbilityConnection() {
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
            System.out.println("远程连接上了======");
            remotePlayerInterfaceProxy = new CrossDevicePlayerInterfaceProxy(iRemoteObject);
        }

        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int i) {
            System.out.println("远程断开了======");
            remotePlayerInterfaceProxy = null;
        }
    };

    /**
     * 初始化设备连接
     */
    public void init(){

//        cameraButtonLayout = new DependentLayout(this);
//        DependentLayout.LayoutConfig cameraButtonLayoutParams = new DependentLayout.LayoutConfig(screenWidth, screenHeight);
//        cameraButtonLayout.setLayoutConfig(cameraButtonLayoutParams);
//        cameraButtonLayout.setAlpha(0.0f);

        emptyDevice = DeviceUtils.getRemoteDevice().isEmpty();
        localOperation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.example.daxiguaforharmony")
                .withAbilityName("com.example.daxiguaforharmony.PlayAbility")
                .withFlags(Intent.FLAG_START_FOREGROUND_ABILITY)
                .build();
        localIntent = new Intent();
        localIntent.setOperation(localOperation);
        IntentParams params = new IntentParams();
        params.setParam("score", 1234);
        localIntent.replaceParams(params);

        try {
            connectAbility(localIntent, localAbilityConnection);
        }catch (Exception e) {
            e.printStackTrace();
        }

        if(!emptyDevice) {
            remoteOperation = new Intent.OperationBuilder()
                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
                    .withBundleName("com.example.daxiguaforharmony")
                    .withAbilityName("com.example.daxiguaforharmony.PlayAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();

            remoteMainOperation = new Intent.OperationBuilder()
                    .withDeviceId(DeviceUtils.getRemoteDevice().get(0).getDeviceId())
                    .withBundleName("com.example.daxiguaforharmony")
                    .withAbilityName("com.example.daxiguaforharmony.MainAbility")
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();

            remoteIntent = new Intent();
            remoteIntent.setOperation(remoteOperation);

            remoteMainIntent = new Intent();
            remoteMainIntent.setOperation(remoteMainOperation);
        } else {
            //Log
            System.out.println("Device List is Empty!!!");
        }
    }



    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);

    }
    @Override
    public boolean onStartContinuation() {
        return true;
    }

    private boolean connectRemoteServices() {
        boolean success = false;
        if(!DeviceUtils.getRemoteDevice().isEmpty()) {
            try {
                success = connectAbility(remoteIntent, remoteAbilityConnection);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        return success;
    }

    @Override
    public boolean onSaveData(IntentParams intentParams) {
        intentParams.setParam("data","remote");
        return true;
    }

    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        data = intentParams.getParam("data").toString();
        return true;
    }
    @Override
    public void onCompleteContinuation(int i) {
        connectRemoteServices();
    }


    /**
     * 查找鸿蒙设备
     */
    public void findDevice()
    {
        DeviceSelectDialog dialog = new DeviceSelectDialog(getContext());
        dialog.setListener(deviceInfo -> {
            LogUtil.debug(TAG, deviceInfo.getDeviceName().toString());
            System.out.println(TAG+" "+deviceInfo.getDeviceName().toString());
            continueAbility(deviceInfo.getDeviceId());
            dialog.hide();
        });
        dialog.show();
    }

    public class MyEvenHandler extends EventHandler {
        public MyEvenHandler(EventRunner runner, int score ) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            LogUtil.info(TAG, "ability  event====：" + event.toString());
            System.out.println( "ability  event====：" + event.toString());
            switch (event.eventId) {
                case 1:
                    //show_process(progressBar);
                    break;
                case CURRENT_SCORE:
                    if(isConnect) {
                        cachedThreadPool.execute(() -> {
                            try {
                                remotePlayerInterfaceProxy.sendCommand(CURRENT_SCORE, score);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    cachedThreadPool.execute(() -> {
                        try {
                            localPlayerInterfaceProxy.sendCommand(CURRENT_SCORE, score);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    break;
                case UPDATE_PROGRESS:
                    if(isConnect) {
                        cachedThreadPool.execute(() -> {
                            try {
                                remotePlayerInterfaceProxy.sendCommand(UPDATE_PROGRESS, 1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                    cachedThreadPool.execute(() -> {
                        try {
                            localPlayerInterfaceProxy.sendCommand(UPDATE_PROGRESS, 1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    }


}
